package cn.net.isir.utils;

import org.apache.poi.hssf.usermodel.*;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * @author liuxubo
 * @filename ExcelExportUtils.java
 * @package cn.net.isir.utils
 * @email lxb@isir.net.cn
 * @date 2019/03/12
 * @comment
 * @since 1.8
 */
public class ExcelExportUtils {
    public static void writeExcelOutputStream(OutputStream outputStream, String[] names, List<List<Object>> data) {
        // 创建工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建sheet页
        HSSFSheet sheet = workbook.createSheet();
        HSSFRow row;
        HSSFCell cell;
        HSSFCellStyle style;
        HSSFFont font;
        int currentRowIndex = 0;
        int currentColumnIndex = 0;
        // 设置标题格式
        style = workbook.createCellStyle();
        font = workbook.createFont();
        font.setBold(true);
        style.setFont(font);
        // 设置标题内容
        row = sheet.createRow(currentRowIndex);
        for (int i = 0; i < names.length; i++) {
            cell = row.createCell(i);
            cell.setCellStyle(style);
            cell.setCellValue(names[i]);
        }
        // 设置正文字体
        font.setBold(false);
        style.setFont(font);
        // 设置数据内容
        for (List<Object> datum : data) {
            row = sheet.createRow(++currentRowIndex);
            for (int i = 0; i < datum.size(); i++) {
                cell = row.createCell(i);
                cell.setCellStyle(style);
                cell.setCellValue(String.valueOf(datum.get(i)));
            }
        }
        try {
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
